package com.ts.file;

import com.ts.comm.SysString;
import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * xml操作工具类
 * Created by xhc on 2017-3-23.
 */
public class SysXML {
    /**
     * 将InputStream输入流解析为Document对象
     *
     * @param insXML
     * @return
     */
    public static Document parse(InputStream insXML) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        Document document = null;
        try {
            document = saxReader.read(insXML);
        } catch (DocumentException e) {
            throw e;
        }
        return document;
    }

    /**
     * 将Xml字符串解析为Document对象
     *
     * @param pStrXml
     * @return
     */
    public static Document parse(String pStrXml) throws DocumentException {
        String strTitle = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        Document document = null;
        try {
            if (pStrXml.indexOf("<?xml") < 0)
                pStrXml = strTitle + pStrXml;
            document = DocumentHelper.parseText(pStrXml);
        } catch (DocumentException e) {
            throw e;
        }
        return document;
    }

    /**
     * 遍历指定节点的所有属性
     *
     * @param e
     * @return 节点属性的list集合
     */
    public static List<Attribute> getAttributeList(Element e) {
        if (e == null)
            return null;
        List<Attribute> attributeList = new ArrayList<Attribute>();
        Iterator<Attribute> atrIterator = e.attributeIterator();
        if (atrIterator == null)
            return null;
        while (atrIterator.hasNext()) {
            Attribute attribute = atrIterator.next();
            attributeList.add(attribute);
        }
        return attributeList;
    }

    /**
     * 得到指定节点的指定属性
     *
     * @param element  指定的元素
     * @param attrName 属性名称
     * @return Attribute
     */
    public static Attribute getAttribute(Element element, String attrName) {
        attrName = attrName.trim();
        if (element == null) {
            return null;
        }
        Attribute attribute = null;
        if (SysString.isEmpty(attrName)) {
            attribute = element.attribute(attrName);
        }
        return attribute;
    }

    /**
     * 得到指定节点的所有属性及属性值
     *
     * @return 属性集合
     */
    public static HashMap<String, String> getNodeAttrMap(Element e) {
        HashMap<String, String> attrMap = new HashMap<String, String>();
        if (e == null) {
            return null;
        }
        List<Attribute> attributes = getAttributeList(e);
        if (attributes == null) {
            return null;
        }
        for (Attribute atr : attributes) {
            String attrValueString = e.attributeValue(atr.getName());
            attrMap.put(atr.getName(), attrValueString);
        }
        return attrMap;
    }
}
